<template>
  <div>
    <el-select class="width100" v-model="selectValue" autocomplete :disabled="disabled" :style="customStyle"
               :placeholder="tips?tips:placeholder" :filterable="filterable" :clearable="false" @change="changHandl">
      <el-option
        v-for="item in options"
        :key="item.key"
        :label="item.label"
        :value="item.value">
      </el-option>
    </el-select>
  </div>
</template>

<script>
export default {
  name: 'project-select',
  componentName: 'projectSelect',
  data() {
    return {
      options: [],
      selectValue: null
    }
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否初始化值
    initValues: {
      type: Boolean,
      default: false
    },
    customStyle: {
      type: Object,
      default() {
        return {}
      }
    },
    // 提示字符串
    placeholder: {
      type: String,
      defult: '请选择'
    },
    // 指定选择项目的状态
    status: {
      type: String,
      default() {
        return ''
      }
    },
    // 接受外部v-model传入的值，必须使用value
    value: {
      type: [String, Number]
    },
    tips: {
      type: String
    },
    filterable: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    // 判断下拉框的值是否有改变
    selectValue(val, oldVal) {
      if (val === '') {
        this.selectValue = null
      }
      if (val !== oldVal) {
        this.$emit('input', this.selectValue)
      }
    },
    value(val) {
      if (typeof val === 'number') {
        this.selectValue = val.toString()
      } else {
        this.selectValue = val
      }
    }
  },
  created() {
    let sysInfoStr = JSON.parse(sessionStorage.getItem('sysInfo') || '{}')
    // 远程请求回来的数据
    this.$http({
      url: '/monitor/project/list4select',
      method: 'get',
      params: {
        'syscode': sysInfoStr.syscode
      }
    }).then(({data}) => {
      if (data && data.code === 0) {
        for (let i = 0; i < data.list.length; i++) {
          this.options[i] = {}
          this.options[i].label = data.list[i]['label']
          this.options[i].value = data.list[i]['value']
          this.options[i].key = i
        }

        // 默认选中第一个
        if (this.initValues && data.list.length > 0) {
          this.selectValue = data.list[0].value
          this.$emit('initProjected', data.list[0].value)
        }
        this.$forceUpdate()
      }
    })
  },
  methods: {
    changHandl(val) {
      this.$emit('change', val)
    }
  }
}
</script>
